package com.my.test.doc;

import java.io.OutputStream;

import org.docx4j.Docx4J;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.jaxb.Context;
import org.docx4j.model.fields.FieldUpdater;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.RFonts;

public class Doc2Pdf {

	static String inputfilepath = "/Users/zongbo/Downloads/测试_结果.docx"; // to generate a docx (and PDF output)
																		// containing font samples

	// Config for non-command line use
	static {

		// URL of converter instance
		// Docx4jProperties.setProperty("com.plutext.converter.URL",
		// "http://localhost:9016/v1/00000000-0000-0000-0000-000000000000/convert");

		// XSL-FO only
		saveFO = true;
	}

	// For demo/debugging purposes, save the intermediate XSL FO
	// Don't do this in production!
	static boolean saveFO;

	public static void main(String[] args) throws Exception {

		try {
			// getInputFilePath(args);
		} catch (IllegalArgumentException e) {
		}

		// Font regex (optional)
		// Set regex if you want to restrict to some defined subset of fonts
		// Here we have to do this before calling createContent,
		// since that discovers fonts
		String regex = null;
		// Windows:
		// String
		// regex=".*(calibri|camb|cour|arial|symb|times|Times|zapf).*";
		// regex=".*(宋体|calibri|camb|cour|arial|times|comic|georgia|impact|LSANS|pala|tahoma|trebuc|verdana|symbol|webdings|wingding).*";
		// Mac
		// String
		// regex=".*(华文宋体|宋体|Courier New|Arial|Times New Roman|Comic
		// Sans|Georgia|Impact|Lucida Console|Lucida Sans Unicode|Palatino
		// Linotype|Tahoma|Trebuchet|Verdana|Symbol|Webdings|Wingdings|MS Sans Serif|MS
		// Serif).*";
		// PhysicalFonts.setRegex(regex);

		// Document loading (required)
		WordprocessingMLPackage wordMLPackage;
		// if (inputfilepath==null) {
		// // Create a docx
		// System.out.println("No imput path passed, creating dummy document");
		// wordMLPackage = WordprocessingMLPackage.createPackage();
		// SampleDocument.createContent(wordMLPackage.getMainDocumentPart());
		// } else {
		// Load .docx or Flat OPC .xml
		System.out.println("Loading file from " + inputfilepath);
		wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
		// }

		// Refresh the values of DOCPROPERTY fields
		FieldUpdater updater = new FieldUpdater(wordMLPackage);
		updater.update(true);

		String outputfilepath;
		// if (inputfilepath==null) {
		// outputfilepath = System.getProperty("user.dir") + "/OUT_FontContent.pdf";
		// } else {
		outputfilepath = "/Users/zongbo/Downloads/测试_结果.pdf";
		// }
		// Mapper fontMapper = new IdentityPlusMapper();
		// fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
		// fontMapper.put("宋体",PhysicalFonts.get("SimSun"));
		// fontMapper.put("微软雅黑",PhysicalFonts.get("Microsoft Yahei"));
		// fontMapper.put("黑体",PhysicalFonts.get("SimHei"));
		// fontMapper.put("楷体",PhysicalFonts.get("KaiTi"));
		// fontMapper.put("新宋体",PhysicalFonts.get("NSimSun"));
		// fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
		// fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
		// fontMapper.put("宋体扩展",PhysicalFonts.get("simsun-extB"));
		// fontMapper.put("仿宋",PhysicalFonts.get("FangSong"));
		// fontMapper.put("仿宋_GB2312",PhysicalFonts.get("FangSong_GB2312"));
		// fontMapper.put("幼圆",PhysicalFonts.get("YouYuan"));
		// fontMapper.put("华文宋体",PhysicalFonts.get("STSong"));
		// fontMapper.put("华文中宋",PhysicalFonts.get("STZhongsong"));
		//
		// wordMLPackage.setFontMapper(fontMapper);
		// All methods write to an output stream
		OutputStream os = new java.io.FileOutputStream(outputfilepath);

		// if (!Docx4J.pdfViaFO()) {
		//
		// // Since 3.3.0, Plutext's PDF Converter is used by default
		//
		// System.out.println("Using Plutext's PDF Converter; add docx4j-export-fo if
		// you don't want that");
		//
		// try {
		// Docx4J.toPDF(wordMLPackage, os);
		// } catch (Docx4JException e) {
		// e.printStackTrace();
		// // What did we write?
		// IOUtils.closeQuietly(os);
		//// System.out.println(
		//// FileUtils.readFileToString(new File(outputfilepath)));
		// if (e.getCause()!=null
		// && e.getCause() instanceof ConversionException) {
		//
		// ConversionException ce = (ConversionException)e.getCause();
		// ce.printStackTrace();
		// }
		// }
		// System.out.println("Saved: " + outputfilepath);
		//
		// return;
		// }

		System.out.println("Attempting to use XSL FO");

		/**
		 * Demo of PDF output.
		 * 
		 * PDF output is via XSL FO. First XSL FO is created, then FOP is used to
		 * convert that to PDF.
		 * 
		 * Don't worry if you get a class not found warning relating to batik. It
		 * doesn't matter.
		 * 
		 * If you don't have logging configured, your PDF will say "TO HIDE THESE
		 * MESSAGES, TURN OFF debug level logging for
		 * org.docx4j.convert.out.pdf.viaXSLFO". The thinking is that you need to be
		 * able to be warned if there are things in your docx which the PDF output
		 * doesn't support...
		 * 
		 * docx4j used to also support creating PDF via iText and via HTML. As of docx4j
		 * 2.5.0, only viaXSLFO is supported. The viaIText and viaHTML source code can
		 * be found in src/docx4j-extras directory
		 *
		 */

		/*
		 * NOT WORKING?
		 * 
		 * If you are getting:
		 * 
		 * "fo:layout-master-set" must be declared before "fo:page-sequence"
		 * 
		 * please check:
		 * 
		 * 1. the jaxb-xslfo jar is on your classpath
		 * 
		 * 2. that there is no stack trace earlier in the logs
		 * 
		 * 3. your JVM has adequate memory, eg
		 * 
		 * -Xmx1G -XX:MaxPermSize=128m
		 * 
		 */

		// Set up font mapper (optional)
		Mapper fontMapper = new IdentityPlusMapper();
		wordMLPackage.setFontMapper(fontMapper);

//		 fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
//		 fontMapper.put("宋体",PhysicalFonts.get("SimSun"));
//		 fontMapper.put("微软雅黑",PhysicalFonts.get("Microsoft Yahei"));
//		 fontMapper.put("黑体",PhysicalFonts.get("SimHei"));
//		 fontMapper.put("楷体",PhysicalFonts.get("KaiTi"));
//		 fontMapper.put("新宋体",PhysicalFonts.get("NSimSun"));
//		 fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
//		 fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
//		 fontMapper.put("宋体扩展",PhysicalFonts.get("simsun-extB"));
//		 fontMapper.put("仿宋",PhysicalFonts.get("FangSong"));
//		 fontMapper.put("仿宋_GB2312",PhysicalFonts.get("FangSong_GB2312"));
//		 fontMapper.put("幼圆",PhysicalFonts.get("YouYuan"));
//		 fontMapper.put("华文宋体",PhysicalFonts.get("STSong"));
//		 fontMapper.put("华文中宋",PhysicalFonts.get("STZhongsong"));
		// 设置文件默认字体
		RFonts rfonts = Context.getWmlObjectFactory().createRFonts();
		rfonts.setAsciiTheme(null);
		rfonts.setAscii("SimSun");//默认设置为宋体，要求服务器要安装此字体，文档中只要有几个字是宋体都不会乱码。但是默认设置为其他字体就不行。
		wordMLPackage.getMainDocumentPart().getPropertyResolver().getDocumentDefaultRPr().setRFonts(rfonts);

		FOSettings foSettings = Docx4J.createFOSettings();
		if (saveFO) {
			foSettings.setFoDumpFile(new java.io.File(inputfilepath + ".fo"));
		}
		foSettings.setWmlPackage(wordMLPackage);

		// Document format:
		// The default implementation of the FORenderer that uses Apache Fop will output
		// a PDF document if nothing is passed via
		// foSettings.setApacheFopMime(apacheFopMime)
		// apacheFopMime can be any of the output formats defined in
		// org.apache.fop.apps.MimeConstants eg
		// org.apache.fop.apps.MimeConstants.MIME_FOP_IF or
		// FOSettings.INTERNAL_FO_MIME if you want the fo document as the result.
		// foSettings.setApacheFopMime(FOSettings.INTERNAL_FO_MIME);

		// Specify whether PDF export uses XSLT or not to create the FO
		// (XSLT takes longer, but is more complete).

		// Don't care what type of exporter you use
		Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

		// Prefer the exporter, that uses a xsl transformation
		// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

		// Prefer the exporter, that doesn't use a xsl transformation (= uses a visitor)
		// .. faster, but not yet at feature parity
		// Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_NONXSL);

		System.out.println("Saved: " + outputfilepath);

		// Clean up, so any ObfuscatedFontPart temp files can be deleted
		if (wordMLPackage.getMainDocumentPart().getFontTablePart() != null) {
			wordMLPackage.getMainDocumentPart().getFontTablePart().deleteEmbeddedFontTempFiles();
		}
		// This would also do it, via finalize() methods
		updater = null;
		foSettings = null;
		wordMLPackage = null;

	}

}
